package com.example.controller;

import com.example.entity.MyResponseEntity;
import com.example.entity.Perm;
import com.example.service.PermService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author fyxw
 */
@RestController
@RequestMapping("/perm")
public class PermController {
    private final PermService service;

    public PermController(PermService service) {
        this.service = service;
    }

    @PostMapping
    public MyResponseEntity<?> addPerm(@RequestBody Perm perm) {
        service.addPerm(perm);
        return new MyResponseEntity<>(200, "添加成功", perm);
    }

    @DeleteMapping("/{id}")
    public MyResponseEntity<?> deletePerm(@PathVariable int id) {
        if (service.deletePerm(id)) {
            return new MyResponseEntity<>(200, "删除成功", null);
        }
        return new MyResponseEntity<>(404, "删除失败, 无该Perm", null);
    }

    @PutMapping
    public MyResponseEntity<?> updatePerm(@RequestBody @Valid Perm perm) {
        // 若perm对象id为空，会产生空指针异常，已使用全局异常捕捉该异常，无需手动处理
        if (service.updatePerm(perm)) {
            return new MyResponseEntity<>(200, "修改成功", null);
        }
        return new MyResponseEntity<>(404, "修改失败", null);
    }

    @GetMapping("/{id}")
    public MyResponseEntity<?> findPerm(@PathVariable int id) {
        final Perm perm = service.findPermById(id);
        return new MyResponseEntity<>(200, "查询成功", perm);
    }

    @GetMapping("/{startPage}/{pageSize}")
    public MyResponseEntity<?> findAllRes(@PathVariable("startPage") int startPage, @PathVariable("pageSize") int pageSize){
        PageHelper.startPage(startPage, pageSize);
        List<Perm> perms = service.findAll();
        PageInfo<Perm> pageInfo = new PageInfo<>(perms);
        return new MyResponseEntity<>(200,"查询成功",pageInfo);
    }
}
